#include "StdAfx.h"
#include "StatPanel.h"
#include "ColorRGB.h"
#include <sstream>


template <typename T> std::string ToString(const T& t)
{
	std::ostringstream os;
	os << t;
	return os.str();
};

StatPanel::StatPanel()
	: GUINode()
{
	mTime_Label = new FEngine::TextLabel("", 5, 5, 80, 30, 22, FEngine::ColorRGB(0, 0, 0));
	addChild(mTime_Label);
	mFPS_Label = new FEngine::TextLabel("FPS : 0", 5, 35, 80, 30, 22, FEngine::ColorRGB(0, 0, 0));
	addChild(mFPS_Label);
	mFrame_Label = new FEngine::TextLabel("Frame : 0ms", 5, 65, 80, 30, 22, FEngine::ColorRGB(0, 0, 0));
	addChild(mFrame_Label);
	
	mTimeSinceStart			= 0;
	mTimeSinceLastUpdate	= 1000;

	mAverageRecordTime		= 2000;
	mActualRecordedTime		= 0;
	mNumberRenderLoop		= 0;
	mLastAverageFPS			= 0;
	mLastAverageFrame		= 0;
}


StatPanel::~StatPanel()
{
	delete mTime_Label;
	delete mFPS_Label;
	delete mFrame_Label;
}

void StatPanel::update(double _elapsedTime)
{
	FEngine::GUINode::update(_elapsedTime);

	mActualRecordedTime += _elapsedTime;
	mNumberRenderLoop += 1;
	if (mActualRecordedTime >= mAverageRecordTime)
	{
		mLastAverageFPS = (int)(mNumberRenderLoop / (mActualRecordedTime / 1000));
		mLastAverageFrame = mActualRecordedTime / mNumberRenderLoop;
		
		mFPS_Label->setText("FPS : " + ToString(mLastAverageFPS));
		mFrame_Label->setText("Frame : " + ToString(mLastAverageFrame) + "ms");

		mNumberRenderLoop = 0;
		mActualRecordedTime = 0;
	}
	
	mTimeSinceLastUpdate += _elapsedTime;
	mTimeSinceStart += _elapsedTime;
	if (mTimeSinceLastUpdate >= 1000)
	{
		mTimeSinceLastUpdate -= 1000;
		mTime_Label->setText("Time : " + ToString((int)(mTimeSinceStart / 1000.0)) + " seconds");
	}
}

void StatPanel::render(double _elapsedTime)
{
	FEngine::GUINode::render(_elapsedTime);
}
